package cn.sinata.wanglin.neighbor.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.utils.SharedPreferencesUtils;

import butterknife.BindView;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.GroupUserDao;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;

public class EditGroupNickActivity extends TitleActivity {

    @BindView(R.id.et_content)
    EditText et_content;
    private String oldNick;
    private String id;
    private String groupAccount;

    @Override
    protected int setContentId() {
        return R.layout.activity_edit_group_nick;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("修改群昵称");

        id = getIntent().getStringExtra("id");
        groupAccount = getIntent().getStringExtra("groupAccount");
        addRightButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = et_content.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    showToast("群昵称不能为空！");
                    return;
                }
                editNick(content);
            }
        });

        oldNick = getIntent().getStringExtra("nick");
        oldNick=oldNick==null?"":oldNick;
        et_content.setText(oldNick);
        if (oldNick.length() > 10) {
            et_content.setSelection(10);
        } else {
            et_content.setSelection(oldNick.length());
        }
    }

    void editNick(final String content){
        showDialog();
        String userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.editGroupMember(userId,id,content)
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        String url = SharedPreferencesUtils.getString(Constant.SP_HEADURL);
                        String account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);
                        GroupUserDao.getInstance(mContext).saveGroupUser(groupAccount,account,content,url);
                        Intent intent = new Intent();
                        intent.putExtra("nick",content);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                });
    }
}
